#include <avr/io.h>
#include "Shared.h"

void SetMclr(uint8_t value)
{
	if((value & 0x0F))
		SETBIT(OUT_PORT,MCLR);
	else
		CLEARBIT(OUT_PORT,MCLR);
}

void ClockControlBits(uint8_t value)
{
	SETBIT(OUT_DDR,PGD);
	uint8_t mask = 0x01;
	while (mask != 0x10)
	{
		if(value & mask)
			OUT_PORT = MSKBIT(OUT_PORT,PGC) | PGD;
		else
			OUT_PORT &= 0xFC;
		mask <<= 1;
		nop();
		SETBIT(OUT_PORT,PGC);
		nop();			
	}
	CLEARBIT(OUT_PORT,PGD);
	CLEARBIT(OUT_PORT,PGC);
}

void ClockLowXTimes(uint8_t value)
{
	SETBIT(OUT_DDR,PGD);
	uint8_t length = value & 0x0F;
	while(length)
	{
		CLEARBIT(OUT_PORT,PGD);
		CLEARBIT(OUT_PORT,PGC);
		length--;
		nop();
		SETBIT(OUT_PORT,PGC);
		nop();
	}
	CLEARBIT(OUT_PORT,PGD);
	CLEARBIT(OUT_PORT,PGC);
}

void ClockByte(uint8_t value)
{
	SETBIT(OUT_DDR,PGD);
	
	uint8_t mask = 0x01;
	while(mask)
	{
		if(value & mask)
			OUT_PORT = MSKBIT(OUT_PORT,PGC) | PGD;
		else
			OUT_PORT &= ~0x03;
		mask <<= 1;
		nop();
		CLEARBIT(OUT_PORT,PGC);
		nop();
	}
	CLEARBIT(OUT_PORT,PGD);
	CLEARBIT(OUT_PORT,PGC);
}

void PinByte(uint8_t *value)
{
	CLEARBIT(OUT_DDR,PGD);
	SETBIT(OUT_PORT,PGD);
	
	uint8_t mask = 0x01;
	while(mask)
	{
		nop();
		SETBIT(OUT_PORT,PGC);
		nop();
		if(CHECKBIT(OUT_PIN,PGD))
			*value |= mask;
		else
			*value &= ~mask;
		CLEARBIT(OUT_PORT,PGC);
		mask <<= 1;	
	}
	CLEARBIT(OUT_PORT,PGD);
}
